import { Button, Input, Popconfirm, Space, Table, Tag } from 'antd'
import React from 'react'
import { deleteParams, addAttrVals } from "../../api/params.js";
import Message from '../../components/Message'

const TablePane = ({ loading, pageText, data, cateId, setData, onEvent, saveAttr }) => {

  const text = '此操作将永久删除该权限, 是否继续?';
  // 表头
  const columns = [
    {
      title: '参数名称',
      dataIndex: 'attr_name',
      key: 'attr_name'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type='link' onClick={() => handleAddOrEdit(record)}>编辑</Button>
          <Popconfirm
            placement="top"
            title={text}
            onConfirm={() => handleDelete(record.attr_id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type='link'>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 表格扩展内容
  const expandedRowTag = (record) => {
    return record.attr_vals.map((item, index) =>
      <Tag key={item + index} color="blue" closable onClose={() => removeParams(record, index)}>{item}</Tag>
    )
  }

  // 点击添加tag
  const showInput = (row) => {
    saveAttr(row)
  };

  // 删除对应的参数可选项
  const removeParams = async (row, index) => {
    row.attr_vals.splice(index, 1);
    const obj = {
      attr_name: row.attr_name,
      attr_sel: row.attr_sel,
      attr_vals: row.attr_vals.join(" "),
    };
    await addAttrVals(cateId, row.attr_id, obj);
    Message("success", "删除成功");
    onEvent()
  };

  // 点击添加/编辑按钮
  const handleAddOrEdit = (row) => {
    setData(row)
  };

  // 删除
  const handleDelete = async (id) => {
    await deleteParams(cateId, id);
    Message("success", "删除成功");
    onEvent()
  };

  return (
    <>
      <Button
        type="primary"
        disabled={cateId ? false : true}
        onClick={() => handleAddOrEdit(null)}
      >{"添加" + pageText}</Button>
      <Table
        loading={loading}
        rowKey="attr_id"
        columns={columns}
        dataSource={data}
        expandable={{
          expandedRowRender: record =>
            <>
              {expandedRowTag(record)}
              <Button size='small' onClick={() => showInput(record)}>+ New Tag</Button>
            </>,
        }}
      />
    </>
  )
}

export default TablePane